<template>
  <div class="app-container">
    <splitpanes class="default-theme">
      <pane min-size="20" size="30" style="padding-right: 20px;">
        <el-form :model="queryParams" ref="queryRef" v-show="showSearch" :inline="true" label-width="68px"
          @submit.prevent>
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入角色名称" clearable @keyup.enter.prevent="handleQuery"
              style="width: 160px;" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasFunc="'role:add'">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" @click="handleUpdate" v-hasFunc="'role:edit'">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" @click="handleDelete" v-hasFunc="'role:del'">删除</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <!-- 表格数据 -->
        <el-table v-loading="loading" :data="roleList" @selection-change="handleSelectionChange"
          @row-click="handleSelectRole" highlight-current-row ref="roleTableRef">
          <el-table-column label="角色名称" prop="name" :show-overflow-tooltip="true" width="150" />
          <el-table-column label="权限字符" prop="code" :show-overflow-tooltip="true" width="150" />
          <el-table-column label="状态" align="center">
            <template #default="scope">
              <el-switch v-model="scope.row.isActive" @change="handleStatusChange(scope.row)"></el-switch>
            </template>
          </el-table-column>
        </el-table>

        <!-- 添加或修改角色配置对话框 -->
        <el-dialog :title="title" v-model="open" width="500px" append-to-body draggable align-center>
          <el-form ref="roleRef" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="角色名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入角色名称" />
            </el-form-item>
            <el-form-item prop="code">
              <template #label>
                <span>
                  <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)" placement="top">
                    <el-icon><question-filled /></el-icon>
                  </el-tooltip>
                  权限字符
                </span>
              </template>
              <el-input v-model="form.code" placeholder="请输入权限字符" />
            </el-form-item>
            <el-form-item label="角色顺序" prop="order">
              <el-input-number v-model="form.order" controls-position="right" :min="0" />
            </el-form-item>
            <el-form-item label="状态">
              <el-radio-group v-model="form.isActive">
                <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="dict.value">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
          </template>
        </el-dialog>

      </pane>
      <pane>
        <el-tabs type="border-card" class="demo-tabs">
          <el-tab-pane v-hasFunc="'role:resource'">
            <template #label>
              <span class="custom-tabs-label">
                <el-icon>
                  <User />
                </el-icon>
                <span>分配用户</span>
              </span>
            </template>
            <template #default>
              <authUser :role-id="highlightRole.id"></authUser>
            </template>
          </el-tab-pane>
          <el-tab-pane>
            <template #label>
              <span class="custom-tabs-label">
                <el-icon>
                  <Coin />
                </el-icon>
                <span>分配资源</span>
              </span>
            </template>
            <template #default>
              <resource :role-id="highlightRole.id"></resource>
            </template>
          </el-tab-pane>
        </el-tabs>
      </pane>

    </splitpanes>
  </div>
</template>

<script setup name="Role">
import { addRole, changeRoleStatus, delRole, getRole, listRole, updateRole } from "@/api/system/role";
import authUser from './authUser.vue'
import resource from './resource.vue'
import { onMounted } from "vue";
const { proxy } = getCurrentInstance();
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");

const roleList = ref([]);
const roleTableRef = ref();
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const highlightRole = ref({});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    code: undefined,
    isActive: undefined
  },
  rules: {
    name: [{ required: true, message: "角色名称不能为空", trigger: "blur" }],
    code: [{ required: true, message: "权限字符不能为空", trigger: "blur" }],
    order: [{ required: true, message: "角色顺序不能为空", trigger: "blur" }]
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询角色列表 */
function getList() {
  loading.value = true;
  return listRole(proxy.addDateRange(queryParams.value, dateRange.value)).then(response => {
    const { result, totalNum } = response;
    roleList.value = result;
    total.value = totalNum;
    loading.value = false;
    return result;
  }).then((data) => {
    if (data && data[0]) {
      highlightRole.value = data[0];
      roleTableRef.value.setCurrentRow(data[0]);
    }
  });;
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 删除按钮操作 */
function handleDelete() {
  const id = highlightRole.value.id;
  if (!id) proxy.$modal.msgWarning("请先选中需要删除的角色");
  let msg = `删除【${highlightRole.value.name}】后将自动解绑相关权限和用户`
  proxy.$modal.confirm(msg).then(function () {
    return delRole(id);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
}

const handleSelectRole = (row) => {
  highlightRole.value = row;
}

/** 角色状态修改 */
function handleStatusChange(row) {
  let text = row.isActive ? "启用" : "停用";
  proxy.$modal.confirm('确认要"' + text + '""' + row.name + '"角色吗?').then(function () {
    return changeRoleStatus(row.id, row.isActive);
  }).then(() => {
    proxy.$modal.msgSuccess(text + "成功");
  }).catch(function () {
    row.isActive = !row.isActive;
  });
}

/** 重置新增的表单以及其他数据  */
function reset() {
  form.value = {
    id: undefined,
    name: undefined,
    code: undefined,
    order: 0,
    isActive: true,
    menuIds: [],
    deptIds: [],
    menuCheckStrictly: true,
    deptCheckStrictly: true,
    remark: undefined
  };
  proxy.resetForm("roleRef");
}

/** 添加角色 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加角色";
}

/** 修改角色 */
function handleUpdate() {
  reset();
  const id = highlightRole.value.id;
  if (!id) proxy.$modal.msgWarning("请先选中需要修改的角色");
  getRole(id).then(response => {
    form.value = response;
    open.value = true;
    title.value = "修改角色";
  });
}


/** 提交按钮 */
function submitForm() {
  proxy.$refs["roleRef"].validate(valid => {
    if (valid) {
      if (form.value.id != undefined) {
        updateRole(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addRole(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}


onMounted(getList)
</script>

<style lang="scss" scoped>
:deep(.el-checkbox.is-disabled) {
  --el-checkbox-disabled-checked-input-fill: var(--el-color-primary-dark-2);
  --el-checkbox-disabled-checked-icon-color: var(--el-text-color-primary)
}
</style>

<style lang="scss" scoped>
.demo-tabs {
  height: 100%;
}

.demo-tabs>.el-tabs__content {
  padding: 32px;
  // color: #6b778c;
  font-size: 32px;
  font-weight: 600;

  .el-tab-pane {
    height: 100%;
    overflow: hidden;
  }
}

.demo-tabs .custom-tabs-label .el-icon {
  vertical-align: middle;
}

.demo-tabs .custom-tabs-label span {
  vertical-align: middle;
  margin-left: 4px;
}
</style>

<style lang="scss">
.splitpanes__pane {
  font-family: Helvetica, Arial, sans-serif;
  background-color: transparent !important;
  transition: none !important;
}

.splitpanes__splitter {
  // background-color: transparent !important;
  background-color: var(--el-fill-color) !important;
  border-left: var(--el-border-color) !important;
  width: 4px !important;
}
</style>
